package com.xujianlun.cpms.controller.shop;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujianlun.cpms.entity.shop.Goods;
import com.xujianlun.cpms.entity.sys.User;
import com.xujianlun.cpms.exception.ServiceException;
import com.xujianlun.cpms.mapper.shop.CartsMapper;
import com.xujianlun.cpms.service.shop.IGoodsService;
import com.xujianlun.cpms.service.sys.IUserService;
import com.xujianlun.cpms.utils.TokenUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

import com.xujianlun.cpms.common.Response;

import com.xujianlun.cpms.service.shop.ICartsService;
import com.xujianlun.cpms.entity.shop.Carts;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xujianlun
 * @since 2022-12-14
 */
@RestController
@RequestMapping("/carts")
public class CartsController {

    @Resource
    private ICartsService cartsService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private IUserService userService;
    @Resource
    private CartsMapper cartsMapper;
    // 新增或者更新
    @Transactional
    @PostMapping
    public Response save(@RequestBody Carts carts) {
        //更新购物车里相同的商品数量
        Integer userId = TokenUtil.getTokenUserId();
        Integer goodsId = carts.getGoodsId();
        Goods goods = goodsService.getById(goodsId);
        Integer num = goods.getStore();//原始的数量
        //当库存没有10时，会提醒商品数量不足无法购买
        if (num==0){
            throw new  ServiceException(-200,"商品数量不足！");
        }
        QueryWrapper<Carts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        queryWrapper.eq("user_id",userId);
        Carts cartsServiceOne = cartsService.getOne(queryWrapper);
        if (cartsServiceOne != null){
            if (num-carts.getNum()<0){
                throw new  ServiceException(-200,"商品数量不足！");
            }
            cartsServiceOne.setNum(cartsServiceOne.getNum()+carts.getNum());
            goods.setStore(num-carts.getNum());//原始的减去现在的
            //进行判断，如果库存数量不足于10，这个货物将会自动下架
            if(num-carts.getNum()==0){
                goods.setStatus(false);
            }
            goodsService.updateById(goods);//更新
            cartsService.updateById(cartsServiceOne);
            return Response.success();
        }
        //新增或者更新
        if (carts.getId() == null){
            if (num-carts.getNum()<0){
                throw new  ServiceException(-200,"商品数量不足！");
            }
            goods.setStore(num-carts.getNum());//原始的减去现在的
            //进行判断，如果库存数量不足于0，这个货物将会自动下架
            if(num-carts.getNum()==0){
                goods.setStatus(false);
            }

            goodsService.updateById(goods);//更新
            carts.setTime(DateUtil.now());
            carts.setUserId(userId);
            cartsService.save(carts);
        }
        return Response.success();
    }
    @Transactional
    @PostMapping("/updateNum/{id}/{num}")
    public Response updateNum(@PathVariable Integer id,@PathVariable Integer num){
        Carts carts = cartsService.getById(id);
        Integer cartsNum = carts.getNum();//购物车本来的数量10
        Integer goodsId = carts.getGoodsId();
        Goods goods = goodsService.getById(goodsId);
        Integer goodsStore = goods.getStore();//goods的库存10
        if (goodsStore-num+cartsNum<0){
            throw new  ServiceException(-200,"商品数量不足！");
        }
        cartsMapper.updateNum(num,id);
        //进行判断，如果库存数量不足于0，这个货物将会自动下架
        if(goodsStore-num+cartsNum==0){
            goods.setStatus(false);
        }
        goods.setStore(goodsStore-num+cartsNum);
        goodsService.updateById(goods);
        return Response.success();
    }
    @Transactional
    @DeleteMapping("/{id}")
    public Response delete(@PathVariable Integer id) {
        //查询carts
        Carts carts = cartsService.getById(id);
        //获取购物车购买的数量
        Integer num = carts.getNum();
        Integer goodsId = carts.getGoodsId();
        Goods goods = goodsService.getById(goodsId);
        boolean b = cartsService.removeById(id);
        //当购物车被删除的时候自然返回goods的库存
        if (b){
            goods.setStore(goods.getStore()+num);
            if(goods.getStore()+num>=1){
//                判断一下是否大于1，若大于自动上架
                goods.setStatus(true);
            }
            goodsService.updateById(goods);
        }
        return Response.success();
    }
    @PostMapping("/batch")
    public Response deleteBatch(@RequestBody List<Integer> ids) {
        cartsService.removeByIds(ids);
        return Response.success();
    }
    @GetMapping("/count")
    public Response count() {
        Integer userId = TokenUtil.getTokenUserId();
        User user = userService.getById(userId);
        if ("ROLE_ADMIN".equals(user.getRole())){
           return Response.success(cartsService.count());
        }
        QueryWrapper<Carts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return Response.success(cartsService.count(queryWrapper));
    }
    @GetMapping
    public Response findAll() {
        return Response.success(cartsService.list());
    }

    @GetMapping("/{id}")
    public Response findOne(@PathVariable Integer id) {
        return Response.success(cartsService.getById(id));
    }

    @GetMapping("/page")
    public Response findPage(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam(defaultValue = "") String name) {
        //根据用户去查询
        Integer tokenUserId = TokenUtil.getTokenUserId();
        User user = userService.getById(tokenUserId);
        String role = user.getRole();
        return Response.success(cartsMapper.pageUserCart(new Page<>(pageNum, pageSize), tokenUserId,role,name));
    }
}

